package cn.jiyun.user.controller;

import cn.jiyun.user.pojo.Users;
import cn.jiyun.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 新增用户
     * @param users
     * @return
     */
    @RequestMapping("/addUser")
    public String addUser(Users users){
        userService.addUser(users);
        return "ok";
    }

    /**
     * 页面跳转
     */
    @RequestMapping("/{page}")
    public String showPage(@PathVariable String page) {
        return page;
    }

    /**
     * 查询所有用户功能
     */
    @RequestMapping("/list")
    public String list(Model model){
        //调用UserService，查询所有用户
        List<Users> usersList = userService.findAll();
        model.addAttribute("list",usersList);
        return "list";
    }

    /**
     * 用户登录功能
     */
    @RequestMapping("/login")
    public String login(Users users, HttpSession session){
        //调用service，根据用户名和密码查询用户
        Users loginUser = userService.login(users);
        if(loginUser!=null){
            //将用户存入session
            session.setAttribute("loginUser",loginUser);
            //重定向到查询用户列表功能
            return "redirect:/users/list";
        }
        //登录失败，重新登录
        return "tologin";
    }

}
